function xnew = combine_matcells( cname,rname,mnames,titulo,div,varargin ); 
% =====================================================================
% COMBINE_MATCELLS.M 
% 
% function xnew = combine_matcells( cname,rname,mnames,titulo,div,varargin);
%
% Create a Cell by combining K matrices or cells into a single cell 
% Each of variable number of matrices must be of dimension [r c] 
% 
% CNAME     Cell with column names [c 1] 
% RNAME     Cell with row    names [c 1] 
% MNAMES    Cell [K 1] or [1 1] with names of matrices 
% TITULO    Title for table 
% DIV       Divisor for elements of the matrices in each cell 
%           Default is ' '
% Variable number of matrices 
% 
% Note 
% If called as combine_matcells( [],[],[],[],div,varargin )
% Output cell will be of same size as input matrices 
% OR 
% Use COMBINE_CELLS for simple concatenation of matrices and cells 
%
% Alejandro Justiniano 9/8/2005 
% =================================================================
nx = length( varargin ) ; 
x1 = varargin{1}; 
[nr,nc] = size( x1 ); 
clear x1; 

ind = 0; 
xnew = emptycell( nr + 2 , nc + 1 ); 
if ~isempty( cname ) 
    xnew(2,2:end) = ( cname(:) )'; 
    ind = ind + 1; 
end 
if ~isempty( rname )
    ind = ind + 1; 
    xnew(3:end,1) = rname(:)'; 
end 
if ~isempty( titulo );
    ind = ind + 1; 
    xnew( 1, 1 ) = cellstr( titulo ); 
end

if isempty( div ); 
    div = ' '; 
end 

if ~isempty( mnames);
    ind = ind + 1;
    mnames = mnames(:) ;
    temp = length( mnames ); 
    tcell = [mnames{1}];
    if temp == nx
        ii=2;
        for ii = 2:nx
            tcell = [tcell,div,mnames{ii}];
        end
        xnew(2,1) = cellstr( tcell );
        clear tcell ii;
    elseif temp == 1
        xnew(2,1) = cellstr( mnames );
    else
        error('Input MNAMES must match number of variable inputs')
    end
end 

tcell = emptycell( nr , nc ); 

ii = 1;
for ii = 1:nx ;

    xt = varargin{ii};
    if isnumeric( xt ) == 1 ;
        xt = num2cprec( xt ) ;
    end

    jj = 1 ;
    for jj =1:nr ;
        kk = 1;
        for kk = 1:nc;

            if ii > 1
                temp = cellstr( [char(tcell(jj,kk)),div, char( xt(jj,kk) )] );
                tcell( jj,kk) = temp ;
            else
                tcell( jj,kk ) = xt( jj , kk );
            end

        end
    end

    clear xt;

end
if ind > 0 
xnew(3:end,2:end) = tcell ; 
else 
    xnew = tcell ; 
end 



        